<template>
  <div class="mod-config">
    <basic-container>
      <el-tabs v-model="activeName" type="card" @tab-click="handleTabChangeClick">
        <el-tab-pane label="全部订单" name="0"></el-tab-pane>
        <el-tab-pane label="待付款" name="1"></el-tab-pane>
        <el-tab-pane label="待发货" name="2"></el-tab-pane>
        <el-tab-pane label="待收货" name="3"></el-tab-pane>
        <el-tab-pane label="已完成" name="4"></el-tab-pane>
        <el-tab-pane label="待评价" name="5"></el-tab-pane>
        <el-tab-pane label="已取消" name="6"></el-tab-pane>
        <el-tab-pane label="已退款" name="7"></el-tab-pane>
        <el-tab-pane label="已退货" name="8"></el-tab-pane>
      </el-tabs>

      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="订单编号" prop="id">
          <el-input
            v-model.trim="queryParams.id"
            placeholder="请输入订单编号"
            clearable
            size="small"
            @keyup.enter.native="getDataList"
          />
        </el-form-item>

        <!-- <el-form-item label="订单类型" prop="orderType">
          <el-select
            v-model="queryParams.orderType"
            filterable
            placeholder="请选择订单状态"
            clearable
            size="small"
            class="margin-left-xs"
          >
            <el-option
              v-for="dict in orderTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item> -->

        <el-form-item label="推广渠道" prop="channelCode">
          <el-select
            v-model="queryParams.channelCode"
            filterable
            placeholder="请选择推广渠道"
            clearable
            size="small"
            class="margin-left-xs"
          >
            <el-option
              v-for="dict in channelList"
              :key="dict.channelCode"
              :label="dict.channelName"
              :value="dict.channelCode"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="收货人电话" prop="contactNumber">
          <el-input
            v-model.trim="queryParams.contactNumber"
            placeholder="请输入下单平台"
            clearable
            size="small"
            @keyup.enter.native="getDataList"
          />
        </el-form-item>

        <!-- <el-form-item label="销售代表" prop="platform">
          <el-input
            v-model.trim="queryParams.platform"
            placeholder="请输入下单平台"
            clearable
            size="small"
            @keyup.enter.native="getDataList"
          />
        </el-form-item> -->

        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="getDataList"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>

      <div class="avue-crud">
        <el-table :data="dataList" border v-loading="dataListLoading">
          <el-table-column
            type="index"
            header-align="center"
            :index="indexMethod"
            align="center"
            label="编号"
          >
          </el-table-column>
          <el-table-column
            prop="id"
            header-align="center"
            align="center"
            label="订单号"
            width="150">
          </el-table-column>
          <el-table-column
            prop="id"
            header-align="center"
            align="center"
            label="订单状态"
            width="80"
          >
            <template slot-scope="{row}">
              <el-tag type="danger" v-if="row.orderStatus === orderStatusEnum.pending">待支付</el-tag>
              <el-tag type="info" v-else-if="row.orderStatus === orderStatusEnum.canceled">已取消</el-tag>
              <el-tag v-else-if="row.orderStatus === orderStatusEnum.processed">待发货</el-tag>
              <el-tag type="info" v-else-if="row.orderStatus === orderStatusEnum.refund">已退款</el-tag>
              <el-tag type="warning" v-else-if="row.orderStatus === orderStatusEnum.shipped">待收货</el-tag>
              <el-tag type="info" v-else-if="row.orderStatus === orderStatusEnum.return">已退货</el-tag>
              <el-tag type="success" v-else-if="row.orderStatus === orderStatusEnum.complete">已完成</el-tag>
              <el-tag type="success" v-else-if="row.orderStatus === orderStatusEnum.comment">已评价</el-tag>
              <el-tag type="danger" v-else>未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            prop="id"
            header-align="center"
            align="center"
            label="推广渠道"
            width="120">
            <template slot-scope="{row}">
              <span v-if="row.channelCode === 'pt'">高个子平台</span>
            </template>
          </el-table-column>
          <el-table-column label="商品sku详情" align="center" prop>
            <el-table-column
              label="sku简称"
              :prop="'skuDetails.0.skuShortName'"
              align="center"
              width="120">
              <template slot-scope="{row}">
                <span v-if="row.orderType == orderTypeEnum.sku">{{ row.skuDetails[0].skuShortName }}</span>
                <span v-else-if="row.orderType == orderTypeEnum.equity">{{ row.skuDetails[0].skuName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              label="罐装数量"
              :prop="'skuDetails.0.canningCount'"
              align="center"
              width="100">
            </el-table-column>
            <el-table-column
              label="袋装数量"
              :prop="'skuDetails.0.bagCount'"
              align="center"
              width="100">
            </el-table-column>
            <el-table-column
              label="条装数量"
              :prop="'skuDetails.0.stripCount'"
              align="center"
              width="100">
            </el-table-column>
            <el-table-column
              label="购买数量"
              align="center"
              width="100">
              <template slot-scope="{row}">
                <span>×</span>
                <span style="margin-left:4px">{{row.skuDetails[0].buyCount}}</span>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="收货人详情" align="center" prop>
            <el-table-column
              label="详细地址"
              align="center"
              width="250"
              :formatter="formatAddress">
            </el-table-column>
            <el-table-column
              label="收货人"
              align="center"
              prop="contacts"
              width="120">
            </el-table-column>
            <el-table-column
              label="联系电话"
              align="center"
              prop="contactNumber"
              width="120">
            </el-table-column>
            <el-table-column
              label="买家留言"
              align="center"
              prop="remark"
              width="120">
            </el-table-column>
          </el-table-column>

          <el-table-column label="订单金额详情" align="center" prop>
            <el-table-column
              label="订单金额"
              prop="sourceOrderPrice"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              label="实际金额"
              prop="orderPrice"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              label="优惠金额"
              prop="couponPrice"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              label="实付金额"
              prop="payPrice"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              label="钱包抵扣"
              prop="walletPrice"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
          </el-table-column>

          <el-table-column label="分润详情" align="center" prop>
            <el-table-column
              label="获取积分"
              prop="totalPoint"
              align="center"
              width="120">
            </el-table-column>
            <el-table-column
              label="一级分润"
              prop="totalFirstProfit"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
            <el-table-column
              label="二级分润"
              prop="totalSecondProfit"
              align="center"
              width="120"
              :formatter="formatMoney">
            </el-table-column>
          </el-table-column>
          
          <el-table-column
            prop="createTime"
            header-align="center"
            align="center"
            label="下单时间"
            width="140"
          >
          </el-table-column>
          <el-table-column header-align="center" align="center" label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                icon="el-icon-search"
                @click="handleOrderDetail(scope.row.id)"
                >详情</el-button>
              <el-button
                v-if="permissions.order_delivery_add && scope.row.orderStatus == orderStatusEnum.processed"
                type="text"
                size="small"
                icon="el-icon-position"
                @click="handleDelivery(scope.row)"
                >发货</el-button>
              <el-button
                v-if="permissions.shop_order_refund && scope.row.orderStatus == orderStatusEnum.processed"
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="handleOrderRefund(scope.row.id)"
                >退款</el-button>
              <el-tooltip :content="scope.row.refundReason" placement="top" v-if="permissions.shop_order_refund && scope.row.orderStatus == orderStatusEnum.refund">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-thumb"
                  >退款原因</el-button>
              </el-tooltip>

              <el-button
                v-if="permissions.shop_order_refund && (scope.row.orderStatus == orderStatusEnum.shipped || scope.row.orderStatus == orderStatusEnum.complete || scope.row.orderStatus == orderStatusEnum.comment)"
                type="text"
                size="small"
                icon="el-icon-edit"
                @click="handleOrderReturn(scope.row.id)"
                >退货</el-button>

              <el-tooltip :content="scope.row.returnReason" placement="top" v-if="permissions.shop_order_refund && scope.row.orderStatus == orderStatusEnum.return">
                <el-button
                  type="text"
                  size="small"
                  icon="el-icon-thumb"
                  >退货原因</el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="avue-crud__pagination">
        <el-pagination
          @size-change="sizeChangeHandle"
          @current-change="currentChangeHandle"
          :current-page="queryParams.pageIndex"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.pageSize"
          :total="totalPage"
          background
          layout="total, sizes, prev, pager, next, jumper"
        >
        </el-pagination>
      </div>

      <order-detail
        v-if="visible"
        ref="orderDetailForm"
        @refreshDataList="getDataList"
        :visible.sync="visible">
      </order-detail>

      <delivery
        v-if="visibleDelivery"
        ref="deliveryForm"
        @refreshDataList="getDataList"
        :visible.sync="visibleDelivery">
      </delivery>

    </basic-container>
  </div>
</template>

<script>
import {getPromotionChannelList} from '@/api/shop_user/promotion_channel';
import {fetchList, orderRefund, orderReturn} from '@/api/shop_order/order';
import { mapGetters } from "vuex";
import {orderStatusEnum, deliveryOrderTypeEnum, orderTypeEnum} from '@/const/const';
import OrderDetail from './detail.vue';
import Delivery from './delivery.vue';

export default {
  components:{OrderDetail, Delivery},
  data(){
    return{
      orderTypeEnum,
      orderStatusEnum,
      queryParams: {
        pageIndex: 1,
        pageSize: 10,
        id:'',
        orderType:'',
        orderStatus:'',
        channelCode:''
      },
      activeName:'0',
      dataList: [],

      totalPage: 0,
      dataListLoading: false,

      // 订单类型 1: 普通订单 2: 拼团订单
      orderTypeList: [{
        value: "1",
        label: "普通订单",
      },{
        value: "2",
        label: "拼团订单",
      }],

      channelList:[],
      visible:false,
      visibleDelivery:false
    }
  },
  created(){
    this.init()
  },
  computed: {
    ...mapGetters(["permissions"]),
  },
  methods:{

    /**
     * 初始化
     */
    init(){
      // 获取所有渠道
      getPromotionChannelList().then(res=>{
        this.channelList = res.data.data
      })
      this.getDataList()
    },

    /**
     * 获取数据列表
     */
    getDataList() {
      this.dataListLoading = true;
      fetchList(
        Object.assign({
          id: this.queryParams.id,
          orderStatus: this.queryParams.orderStatus,
          channelCode: this.queryParams.channelCode,
          contactNumber: this.queryParams.contactNumber,
          current: this.queryParams.pageIndex,
          size: this.queryParams.pageSize
        })
      ).then((response) => {
        this.dataListLoading = false;
        this.dataList = response.data.data.records;
        this.totalPage = response.data.data.total;
        this.formatOrder()
      });
      
    },

    /**
     * 格式化订单数据
     */
    formatOrder(){
      this.dataList.forEach(order=>{
        order.skuDetails.forEach(sku=>{
          sku.skuInfo = JSON.parse(sku.skuInfo)
        })
      })
    },

    /**
     * 收货人地址
     */
    formatAddress(row,column){
      if(row.province && row.city &&  row.area && row.address){
        return `${row.province}${row.city}${row.area}${row.address}`;
      } else {
        return '-'
      }
      
    },

    /**
     * 切换订单状态
     */
    handleTabChangeClick(e){
      switch(e.index){
        case '0':
          // 全部订单
          this.queryParams.orderStatus = ''
          break;
        case '1':
          // 待付款
          this.queryParams.orderStatus = orderStatusEnum.pending
          break;
        case '2':
          // 待发货
          this.queryParams.orderStatus = orderStatusEnum.processed
          break;
        case '3':
          // 待收货
          this.queryParams.orderStatus = orderStatusEnum.shipped
          break;
        case '4':
          // 已完成
          this.queryParams.orderStatus = orderStatusEnum.complete
          break;
        case '5':
          // 待评价
          this.queryParams.orderStatus = orderStatusEnum.comment
          break;
        case '6':
          // 已取消
          this.queryParams.orderStatus = orderStatusEnum.canceled
          break;
        case '7':
          // 已退款
          this.queryParams.orderStatus = orderStatusEnum.refund
          break;
        case '8':
          // 已退货
          this.queryParams.orderStatus = orderStatusEnum.return
          break;
      }
      this.getDataList()
    },

    /**
     * 重置
     */
    resetQuery() {
      this.queryParams.pageIndex = 1;
      this.queryParams.pageSize = 10;
      this.resetForm("queryForm");
      this.getDataList();
    },

    /**
     * 每页数
     */
    sizeChangeHandle(val) {
      this.queryParams.pageSize = val;
      this.queryParams.pageIndex = 1;
      this.getDataList();
    },

    /**
     * 当前页
     */
    currentChangeHandle(val) {
      this.queryParams.pageIndex = val;
      this.getDataList();
    },

    indexMethod(index) {
      return (
        (this.queryParams.pageIndex - 1) * this.queryParams.pageSize + index + 1
      );
    },

    /**
     * 是否显示发货按钮
     */
    hasShowDelivery(row){
    },

    /**
     * 订单详情
     */
    handleOrderDetail(orderId){
      this.visible = true
      this.$nextTick(()=>{
        this.$refs.orderDetailForm.init(orderId)
      })
    },

    /**
     * 发货
     */
    handleDelivery(row){
      this.visibleDelivery = true
      let address = `${row.province}${row.city}${row.area}${row.address}`
      this.$nextTick(()=>{
        this.$refs.deliveryForm.init(row.id, address, row.contacts, row.contactNumber, deliveryOrderTypeEnum.goodsOrder)
      })
    },

    /**
     * 订单退款
     */
    handleOrderRefund(orderId){
      this.$prompt("退款原因", "订单退款", {
        closeOnClickModal: false,
        closeOnPressEscape: false,
        inputType: "textarea",
        inputPattern: /.+$/,
        inputErrorMessage: "退款原因不能为空",
        beforeClose: (action, { inputValue }, done) => {
          if (action !== "confirm") {
            return done();
          }
          const loading = this.$loading({ lock: true });
          let data = {
            id: orderId,
            refundReason: inputValue
          }
          orderRefund(data)
            .then(() => {
              this.getDataList()
              this.$message.success("订单退款成功");
              done();
            })
            .finally(() => {
              loading.close();
            });
        }
      });
    },

    /**
     * 订单退货
     */
    handleOrderReturn(orderId){
      this.$prompt("退货理由", "订单退货", {
        closeOnClickModal: false,
        closeOnPressEscape: false,
        inputType: "textarea",
        inputPattern: /.+$/,
        inputErrorMessage: "退货理由不能为空",
        beforeClose: (action, { inputValue }, done) => {
          if (action !== "confirm") {
            return done();
          }
          const loading = this.$loading({ lock: true });
          let data = {
            id: orderId,
            returnReason: inputValue
          }
          orderReturn(data)
            .then(() => {
              this.getDataList()
              this.$message.success("订单退货成功");
              done();
            })
            .finally(() => {
              loading.close();
            });
        }
      });
    }

  }
}
</script>